package com.dyw.crash;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dyw.crashcatch.CrashFileUtil;
import com.dyw.crashcatch.NativeCrash;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button javaCrashBtn;
    private Button nativeCrashBtn;
    private Button javaCrashInfoBtn;
    private Button nativeCrashInfoBtn;
    private Button deleteCrashBtn;
    private TextView showCrashTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        javaCrashBtn = findViewById(R.id.btn_java_crash);
        nativeCrashBtn = findViewById(R.id.btn_native_crash);
        javaCrashInfoBtn = findViewById(R.id.btn_java_crash_info);
        nativeCrashInfoBtn = findViewById(R.id.btn_native_crash_info);
        deleteCrashBtn = findViewById(R.id.btn_delete_crash);
        showCrashTv = findViewById(R.id.tv_show_crash_info);

        javaCrashBtn.setOnClickListener(this);
        nativeCrashBtn.setOnClickListener(this);
        javaCrashInfoBtn.setOnClickListener(this);
        nativeCrashInfoBtn.setOnClickListener(this);
        deleteCrashBtn.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_java_crash:
                int i = 34 / 0;
                break;
            case R.id.btn_native_crash:
                NativeCrash.triggerNativeCrash();
                break;
            case R.id.btn_java_crash_info:
                setCrashInfo("java_crash", CrashFileUtil.getInstance().getJavaCrashFiles());
                break;
            case R.id.btn_native_crash_info:
                setCrashInfo("native_crash", CrashFileUtil.getInstance().getNativeCrashFiles());
                break;
            case R.id.btn_delete_crash:
                CrashFileUtil.getInstance().deleteCrashFiles();
                setCrashInfo("delete_crash", new ArrayList<>());
                break;
            default:
                break;
        }
    }

    private void setCrashInfo(String type, List<File> files) {
        showCrashTv.setText("");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(type).append("\n");
        if (!files.isEmpty()) {
            for (File file : files) {
                stringBuilder.append(file.getName()).append("\n");
            }
        }
        showCrashTv.setText(stringBuilder);
    }
}